<template>
  <div>
    <!--卡片-->
    <el-card class="box-card">
      <!-- 搜索 -->
      <el-form v-show="showSearch" :model="queryForm" :inline="true" label-width="68px">
        <el-form-item label="" prop="roleName">
          <el-input v-model="queryForm.roleName" placeholder="请输入名称" clearable size="small" prefix-icon="el-icon-search" />
        </el-form-item>
        <el-form-item>
          <el-date-picker
            v-model="createDate"
            :default-time="['00:00:00','23:59:59']"
            size="small"
            style="width: 240px"
            value-format="yyyy-MM-dd HH:mm:ss"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </el-form-item>
        <el-form-item>
          <el-button plain type="primary" icon="el-icon-search" size="mini" @click="searchQuery">搜索</el-button>
          <el-button plain type="warning" icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 新增，编辑，删除，导出 -->
      <el-button
        v-hasPermi="['admin','system:role:add']"
        type="primary"
        small
        icon="el-icon-plus"
        size="mini"
        @click="addDialogVisible = true"
      >新增
      </el-button>
      <el-button
        v-hasPermi="['admin','system:role:edit']"
        :disabled="ids.length===1?false:true"
        type="success"
        small
        icon="el-icon-edit"
        style="margin:10px"
        size="mini"
        @click="editBtn(ids[0])"
      >修改
      </el-button>
      <el-button
        v-hasPermi="['admin','system:role:del']"
        :disabled="ids.length>0?false:true"
        type="danger"
        small
        icon="el-icon-delete"
        style="margin:10px"
        size="mini"
        @click="delAllBtn()"
      >删除
      </el-button>
      <el-button
        v-hasPermi="['admin','system:role:export']"
        type="warning"
        small
        icon="el-icon-download"
        style="margin:10px"
        size="mini"
        @click="exportClick"
      >导出
      </el-button>
      <!-- 搜索，刷新，表头工具栏 -->
      <right-bar :show-search.sync="showSearch" :table-data="tableColumns" @queryTable="refresh()" />

      <!--角色表格-->
      <el-table :data="listForm" stripe style="font-size: 12px;width: 100%" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column v-if="hasTable('roleId',tableColumns)" prop="roleId" label="ID" width="55" />
        <el-table-column v-if="hasTable('roleName',tableColumns)" prop="roleName" label="角色名称" />
        <el-table-column v-if="hasTable('roleKey',tableColumns)" prop="roleKey" label="角色标识" />
        <el-table-column v-if="hasTable('remark',tableColumns)" prop="remark" label="备注" />
        <el-table-column v-if="hasTable('createTime',tableColumns)" prop="createTime" label="创建日期" width="180" />
        <!--操作-->
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button v-hasPermi="['admin','system:role:auth']" type="text" size="mini" @click="authClick(scope.row.roleId)">功能权限</el-button>
            <el-button v-hasPermi="['admin','system:role:edit']" type="text" size="mini" @click="editBtn(scope.row.roleId)">编辑</el-button>
            <el-button v-show="scope.row.roleId!==1" v-hasPermi="['admin','system:role:del']" type="text" size="mini" @click="delBtn(scope.row.roleId)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!--分页区域-->
      <el-pagination
        background
        :current-page="pageNumber"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <!--添加角色对话框-->
    <el-dialog title="添加角色" :close-on-click-modal="false" :visible.sync="addDialogVisible" width="580px" @close="addHandleClose">
      <span>
        <el-form ref="addFormRef" :model="addForm" :rules="addFormRules" label-width="100px">
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="addForm.roleName" />
          </el-form-item>
          <el-form-item label="角色标识" prop="roleKey">
            <el-input v-model="addForm.roleKey" />
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input v-model="addForm.remark" />
          </el-form-item>
          <el-form-item label="数据权限" prop="dataScope">
            <el-select v-model="addForm.dataScope" placeholder="数据范围" style="width: 450px" @change="dataselect(addForm.dataScope)">
              <el-option v-for="item in dataScopeList" :key="item.key" :label="item.label" :value="item.key" />
            </el-select>
          </el-form-item>
          <el-form-item v-if="addForm.dataScope ===2" label="数据权限" prop="dataScope">
            <el-tree
              ref="treeData"
              :data="deptTree"
              :props="deptTreeProps"
              show-checkbox
              node-key="deptId"
              default-expand-all
            />
          </el-form-item>
        </el-form>
      </span>
      <!--底部区域-->
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="addDialogVisible = false">取 消</el-button>
        <el-button size="mini" type="primary" @click="addClick">确 定</el-button>
      </span>
    </el-dialog>

    <!--编辑角色对话框-->
    <el-dialog title="编辑角色" :close-on-click-modal="false" :visible.sync="editDialogVisible" width="580px" @close="editHandleClose">
      <span>
        <el-form ref="editFormRef" :model="editForm" label-width="100px">
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="editForm.roleName" />
          </el-form-item>
          <el-form-item label="角色标识" prop="roleKey">
            <el-input v-model="editForm.roleKey" disabled />
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input v-model="editForm.remark" />
          </el-form-item>
          <el-form-item label="数据权限" prop="dataScope">
            <el-select v-model="editForm.dataScope" placeholder="数据范围" style="width: 450px">
              <el-option v-for="item in dataScopeList" :key="item.key" :label="item.label" :value="item.key" />
            </el-select>
          </el-form-item>
          <el-form-item v-if="editForm.dataScope ===2" label="数据权限" prop="dataScope">
            <el-tree
              ref="treeData"
              :data="deptTree"
              :props="deptTreeProps"
              show-checkbox
              node-key="deptId"
              default-expand-all
              :default-checked-keys="dataDefaultKeys"
            />
          </el-form-item>
        </el-form>
        <!--底部区域-->
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="editDialogVisible = false">取 消</el-button>
        <el-button size="mini" type="primary" @click="editClick">确 定</el-button>
      </span>
    </el-dialog>

    <!--授权对话框-->
    <el-dialog title="功能权限" :close-on-click-modal="false" :visible.sync="allotDialogVisible" width="580px" @close="authDialogClosed">
      <span>
        <el-tree
          ref="treeRef"
          :data="menuTree"
          :props="menuTreeProps"
          show-checkbox
          node-key="menuId"
          default-expand-all
          :default-checked-keys="defaultKeys"
        />
        <!--底部区域-->
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="allotDialogVisible = false">取 消</el-button>
        <el-button size="mini" type="primary" @click="allotClick">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { add, edit, del, getRole, listRole, auth, exportRole } from '@/api/system/role'
import { treeMenu } from '@/api/system/menu'
import { treeDept } from '@/api/system/dept'
import { downloadFile } from '@/utils/index'
export default {
  name: 'Role',
  data() {
    return {
      addDialogVisible: false,
      editDialogVisible: false,
      allotDialogVisible: false,
      dataDialogVisible: false,
      showSearch: true,
      pageNumber: 1,
      pageSize: 10,
      total: 1,
      menuTree: [],
      deptTree: [],
      menuTreeProps: {
        children: 'children',
        label: 'menuName'
      },
      deptTreeProps: {
        children: 'children',
        label: 'deptName'
      },
      dataDefaultKeys: [],
      dataScopeList: [
        {
          key: 1,
          label: '全部'
        }, {
          key: 2,
          label: '自定义'
        }, {
          key: 3,
          label: '本部门及以下部门'
        }, {
          key: 4,
          label: '本部门'
        }
      ],
      role: {
        roleId: '',
        menuIdList: []
      },
      defaultKeys: [],
      ids: [],
      listForm: [],
      addForm: {
        roleName: '',
        roleKey: '',
        remark: '',
        dataScope: '',
        deptList: []
      },
      editForm: {},
      createDate: [],
      queryForm: {
        roleName: '',
        startDate: '',
        endDate: ''
      },
      tableColumns: [{
        label: 'ID',
        value: 'roleId',
        visible: true
      },
      {
        label: '角色名称',
        value: 'roleName',
        visible: true
      },
      {
        label: '角色标识',
        value: 'roleKey',
        visible: true
      },
      {
        label: '备注',
        value: 'remark',
        visible: true
      },
      {
        label: '创建日期',
        value: 'createTime',
        visible: true
      }
      ],
      addFormRules: {
        roleName: [
          { required: true, message: '请输入角色名', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    // 初始化角色列表
    this.initListRole()
  },

  methods: {
    // 查询按钮
    searchQuery() {
      if (this.createDate.length > 0) {
        this.queryForm.startDate = this.createDate[0]
        this.queryForm.endDate = this.createDate[1]
      }
      this.searchListRole()
    },

    // 重置按钮
    resetQuery() {
      this.createDate = []
      this.queryForm = {}
      this.initListRole()
    },

    // 刷新按钮
    refresh() {
      // 根据用户的部门id来查用户列表
      this.searchListRole()
    },

    // 添加按钮
    addBtn() {
      this.addDialogVisible = true
    },
    // 确认添加角色
    addClick() {
      this.$refs.addFormRef.validate(valid => {
        if (!valid) return
        if (this.addForm.dataScope === 2) {
          this.addForm.deptList = [
            ...this.$refs.treeData.getCheckedKeys() // 获取全选的menuId
          ]
        }
        add(this.addForm).then(res => {
          if (res.code === 20000) {
            this.$message.success(res.message)
            // 刷新数据
            this.searchListRole()
          }
          // 关闭对话框
          this.addDialogVisible = false
        })
      })
    },

    // 编辑按钮
    editBtn(id) {
      console.log(this.ids)
      this.editDialogVisible = true
      treeDept().then(res => {
        this.deptTree = res.data
      })
      getRole(id).then(res => {
        if (res.code === 20000) {
          this.editForm = res.data
          this.dataDefaultKeys = res.data.deptIdList
        }
      })
    },
    // 确认编辑角色
    editClick() {
      this.$refs.editFormRef.validate(valid => {
        if (!valid) return
        if (this.editForm.dataScope === 2) {
          this.editForm.deptList = [
            ...this.$refs.treeData.getCheckedKeys() // 获取全选的menuId
          ]
        }
        edit(this.editForm).then(res => {
          if (res.code === 20000) {
            this.$message.success(res.message)
            // 刷新数据
            this.searchListRole()
          }
          // 关闭对话框
          this.editDialogVisible = false
        })
      })
    },

    // 批量删除按钮
    delAllBtn() {
      const data = {
        ids: this.ids
      }
      this.delRole(data)
    },
    // 删除按钮
    delBtn(id) {
      this.ids = []
      this.ids.push(id)
      const data = {
        ids: this.ids
      }
      this.delRole(data)
      this.ids = []
    },

    // 删除方法
    delRole(data) {
      this.$confirm('此操作将永久删除【' + this.ids.length + '条数据】, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 确认操作
        del(data).then(res => {
          if (res.code === 20000) {
            this.$message.success(res.message)
            // 刷新数据
            this.searchListRole()
          }
        })
      })
    },

    // 导出
    exportClick() {
      const tableName = 'role'
      this.$confirm('是否确认导出所有用户数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 确认操作
        exportRole().then(data => {
          downloadFile(data, tableName, 'xlsx')
        })
      })
    },

    // 设置数据权限
    dataselect(dataScope) {
      if (dataScope === 2) {
        treeDept().then(res => {
          this.deptTree = res.data
        })
      }
    },

    // 功能权限确认
    allotClick() {
      this.role.menuIdList = [
        ...this.$refs.treeRef.getCheckedKeys() // 获取全选的menuId
        // ...this.$refs.treeRef.getHalfCheckedKeys() // 获取半选的menuId
      ]
      auth(this.role).then(res => {
        if (res.code === 20000) {
          this.$message.success(res.message)
        } else {
          this.$message.error(res.message)
        }
        // 关闭对话框
        this.allotDialogVisible = false
      })
    },

    // 监听功能权限对话框的关闭事件
    authDialogClosed() {
      this.defaultKeys = []
    },

    // 功能权限点击
    authClick(roleId) {
      this.allotDialogVisible = true
      this.role.roleId = roleId
      treeMenu().then(res => {
        this.menuTree = res.data
      })

      getRole(roleId).then(res => {
        this.defaultKeys = res.data.menuIdList
      })
    },

    // 表格全选
    handleSelectionChange(val) {
      this.ids = []
      for (let index = 0; index < val.length; index++) {
        this.ids.push(val[index].roleId)
      }
      console.log(this.ids)
    },
    // 监听当前页的事件
    handleCurrentChange(pageIndex) {
      this.pageNumber = pageIndex
      this.searchListRole()
    },

    // 监听当前页的条数事件
    handleSizeChange(pageSize) {
      this.pageSize = pageSize
      this.searchListRole()
    },

    // 监听添加角色对话框的关闭事件，重置表单内容
    addHandleClose() {
      this.$refs.addFormRef.resetFields()
      this.addForm.roleIdList = []
    },

    // 监听编辑角色对话框的关闭事件,重置表单内容
    editHandleClose() {
      this.$refs.editFormRef.resetFields()
      this.addForm.roleIdList = []
    },

    // 条件查询
    searchListRole() {
      const page = {
        pageNum: this.pageNumber,
        pageSize: this.pageSize
      }
      listRole(this.queryForm, page).then(res => {
        this.listForm = res.data.records
        this.total = res.data.total
        this.pageNum = res.data.current
      })
    },

    // 初始化角色数据
    initListRole() {
      const page = {
        pageNum: this.pageNumber,
        pageSize: this.pageSize
      }
      listRole(null, page).then(res => {
        this.listForm = res.data.records
        this.total = res.data.total
        this.pageNum = res.data.current
      })
    }
  }
}
</script>

<style scoped>
</style>
